#include "user_smart_config.h"
#include "osapi.h"
#include "at_custom.h"
#include "user_interface.h"
#include "smartconfig.h"
#include "espconn.h"
#include "mem.h"
#include "uart/uart.h"
#include "debug.h"
#include "wifi.h"
WifiCallback wifiCb_temp = NULL;

void ICACHE_FLASH_ATTR
smartconfig_done2(sc_status status, void *pdata) {
	switch (status) {
	case SC_STATUS_WAIT:
		at_port_print("SC_STATUS_WAIT\n");
		break;
	case SC_STATUS_FIND_CHANNEL:
		at_port_print("SC_STATUS_FIND_CHANNEL\n");
		break;
	case SC_STATUS_GETTING_SSID_PSWD:
		at_port_print("SC_STATUS_GETTING_SSID_PSWD\n");
		sc_type *type = pdata;
		if (*type == SC_TYPE_ESPTOUCH) {
			at_port_print("SC_TYPE:SC_TYPE_ESPTOUCH\n");
		} else {
			at_port_print("SC_TYPE:SC_TYPE_AIRKISS\n");
		}
		break;
	case SC_STATUS_LINK:
		at_port_print("SC_STATUS_LINK\n");
		struct station_config *sta_conf = pdata;
		wifi_station_set_config(sta_conf);
		wifi_station_disconnect();
		wifi_station_connect();
		break;
	case SC_STATUS_LINK_OVER:
		at_port_print("SC_STATUS_LINK_OVER\n");
		if (pdata != NULL) {
			uint8 phone_ip[4] = { 0 };
			memcpy(phone_ip, (uint8*) pdata, 4);
			os_printf("Phone	IP:	%d.%d.%d.%d\n", phone_ip[0], phone_ip[1],
					phone_ip[2], phone_ip[3]);
		}

//		smartconfig_stop();
		INFO("wifi set success");
		WIFI_Cache_Connect(wifiCb_temp);
		break;
	}
}



void ICACHE_FLASH_ATTR
user_start_smartconfig( WifiCallback cb) {
	wifiCb_temp = cb;
	bool modeset = wifi_set_opmode(STATION_MODE);
	if (modeset != 0) {
		at_port_print("\r\n wifi_set_opmode yes \r\n");
		smartconfig_start(smartconfig_done2);
		at_port_print("no WIFI cache \r\n");
	} else {
		at_port_print("\r\n wifi_set_opmode no \r\n");
	}
}
